<?php
/*
 * IKPHP 爱客开源社区 @copyright (c) 2012-3000 IKPHP All Rights Reserved 
 * @author 小麦
 * @Email:ikphp@sina.cn 
 * @Time:2014年8月22日22:45:11
 * 个人空间 日记
 */
namespace IKPHP\Apps\Space\Controllers;

use IKPHP\Apps\Space\Controllers;
use IKPHP\Common\Models\User;
use IKPHP\Apps\Space\Models\UserPhoto;
use IKPHP\Apps\Space\Models\UserPhotoAlbum;
use IKPHP\Org\UploadFile;
use IKPHP\Apps\Space\Models\UserFollow;
use IKPHP\Common\Models\Comment;

class PhotosController extends SpaceBaseController
{
	public $userid = 0;
	
    public function initialize()
    {
        parent::initialize();
        // 访问者控制
		if ($this->visitor){
			$this->userid = $this->visitor['userid'];
		}
		$this->user_mod = new User();
    }
 
    public function indexAction($id){
    	if(empty($id)) return $this->error ( '呃...你想要的东西不在这儿' );
    	$userid = $this->isValidUser($id);
    	$strUser = $this->user_mod->getOneUser($userid);
        
    	if($strUser){
    		
    		//查询相册
    		$map = "userid = '$userid'";
    		$count = UserPhotoAlbum::count($map);
			$pager = $this->_pager($count, 10);
			$where = array(
					"columns" => "albumid",
			 		"conditions" => $map,
		 			"order" => "addtime DESC", 
		 			"limit" => array("number"=>$pager->listRows, 'offset'=>$pager->firstRow)
			);
			$list  = UserPhotoAlbum::find($where); 

    	    $arrAlbum = array();
			if(count($list) > 0){
				foreach($list as $key=>$item){
					$arrAlbum[] = UserPhotoAlbum::getOneAlbum($item->albumid);
				}			
			}
			
			//获取最新评论
			$all_photos = UserPhoto::find(array('columns'=>'photoid','conditions'=>"userid = '$userid'")); 
    		$str_pid ='';
			foreach ($all_photos as $ap){
				if(empty($str_pid)){
					$str_pid .= $ap->photoid;
				}else{
					$str_pid .= ','. $ap->photoid;
				}
			}
			$arrNewComment = array();			
			if(!empty($str_pid)){
				$where = "type='UserPhoto' AND userid<>'$userid' AND typeid IN (".$str_pid.")";
				$arrNewComment = Comment::getNewComment($where, 8); 							
			}
			$this->assign('arrNewComment',$arrNewComment);
			///////////////
			
			$this->assign('arrAlbum',$arrAlbum);
			$this->assign('pageUrl', $pager->show());
									
			if($this->userid == $userid){
			 	$title = '我的相册';
			}else{
			 	$title = $strUser['username'].'的相册';
			}
			$this->assign('strUser',$strUser);  	
	    	$this->_config_seo ( array (
				'title' => $title,
				'subtitle'=> '_相册_'.C('ik_site_title'),
				'keywords' => '网络相册,免费相册,相片,照片,相册',
				'description'=> '分享生活中的照片，爱客相册，留住青春，珍藏您一生的记忆！',
	    		'userTitle' => $title
			) );	
				 
		}else{
			return $this->error('呃...你想访问的页面不存在');
		}    	
    }
    public function createAction(){
    	//访问控制
    	if(!$this->visitor){return $this->_redirect('home/user/login');}  
    	$userid = $this->userid;
    	if(IS_POST && $this->security->checkToken()){
    		
    		$data['userid'] = $this->userid;
			$data['albumname'] = $this->_post('albumname');
			$data['albumdesc'] = $this->_post('albumdesc');
			$data['orderid'] = $this->_post('orderid','trim','desc');
			$data['privacy'] = $this->_post('privacy','intval','1');
			$data['isreply'] = $this->_post('isreply','trim','1'); // 1表示允许回复
			$data['addtime'] = $data['uptime'] = time();
			
    		//录入检查
			if( ck_strlen($data ['albumname'])>20){
				return $this->error ('相册名太长啦，最多20个字...^_^！');
			}else if( ck_strlen($data ['albumdesc'])>200){
				return $this->error ('相册描述太多了，最多200个字...^_^！');
			}else if(empty($data ['albumname']) || empty($data ['albumdesc'])){
				return $this->error ('相册标题和描述必须填写！');
			}

			$album_mod = new UserPhotoAlbum();
			//开始创建
			if (false === $album_mod->create ($data)) {
				return $this->error ( $album_mod->getMessages() );
			}else{
				return $this->_redirect('space/photos/upload/'.$album_mod->albumid);
			}
			
    	}else{
			$this->_config_seo ( array (
				'title' => '创建新相册',
				'subtitle'=> '相册_'.C('ik_site_title'),
				'keywords' => '',
				'description'=> '',
			) );
			$this->view->pick('photos/create');   	
    	}
    	
    }
    //上传照片 普通上传
	public function uploadAction($albumid){
    	//访问控制
    	if(!$this->visitor){return $this->_redirect('home/user/login');}  		
		$type = $this->_get('type','trim','');
		$smalltime = $this->_get('time','intval');
		$albumid = intval($albumid);
		$userid = $this->userid;
		
		if($albumid>0){
			//获取相册信息
			$strAlbum = UserPhotoAlbum::getOneAlbum($albumid);
			if($strAlbum && $strAlbum['userid']==$userid){
					if(IS_POST){
							if($this->security->checkToken()){ 
								$res = $this->uploadPhoto($userid,$albumid);
								if ($res){
									return $this->_redirect('space/photos/info/'.$albumid.'?time='.$smalltime);
								}else{
									return $this->error ('上传失败！');
								}								
							}else{
								return $this->error('会话token失败！');
							}
					}else{
						$this->assign('type', $type);
						$this->assign('smalltime',time());
						$this->assign('strAlbum',$strAlbum);
						$this->_config_seo ( array (
								'title' => '上传照片 - '.$strAlbum['albumname']
						) );
						
						$this->_config_seo ( array (
							'title' => '上传照片 - '.$strAlbum['albumname'],
							'subtitle'=> '相册_'.C('ik_site_title'),
							'keywords' => '',
							'description'=> '',
						) );
						$this->view->pick('photos/upload');   					
					}
			}else{
				$this->error('你没有权限更新照片！');
			}
		}else{
			$this->error("你访问的页面不存在");
		}
	}
		
	//ajax上传照片
	public function ajaxupAction(){ 
		if(IS_POST){ 
			$userid = $this->_post('userid','intval');
			$timestamp = $this->_post('timestamp','intval');
			$tokenKey = $this->_post('tokenKey');
			$albumid = $this->_post('albumid','intval');

			if(md5($timestamp+$userid+$albumid) == $tokenKey && !empty($userid) && !empty($albumid) && !empty($timestamp)){
				$res = $this->uploadPhoto($userid, $albumid);
				if ($res){
					$this->ajaxReturn(array('status'=>0, 'text'=>'上传完成'));
				}
			}else{
				$this->ajaxReturn(array('status'=>1, 'text'=>'会话失败'));
			}
		}else{
			$this->error("你访问的页面不存在");
		}
	}
	public function uploadPhoto($userid,$albumid){ 
		$albumid = intval($albumid); 
		$arrJson = array();

		if($this->request->hasFiles() == true && $albumid>0){ 
			//类型判断
			$up_files = $this->request->getUploadedFiles();
			$up_file = $up_files[0];
			$countFile = 0;
			//尺寸判断
			$imageinfo = @getimagesize($_FILES['picfile']['tmp_name']);
			if($imageinfo[0] < 200 || $imageinfo[1] < 200)
			{
				return false;				
			}		
			//大小判断
			if($up_file->getSize()/1024 > C('ik_attr_allow_size'))
			{
				return false;				
			}	

			//保存文件夹
            $avatar_dir = 'photo/'.$userid.'/'.$albumid.'/';	
			//开始保存
			$upload = new UploadFile(array('autoSub'=>false,'savePath'=>$avatar_dir));
			$result = $upload->upload();
			
			if(!empty($result)){
				$photo_mod = new UserPhoto();
				$arrData = array(
						'userid'	=> $userid,
						'albumid'	=> $albumid,
						'photopath' => $result[0]['savepath'],
						'photoname' => $result[0]['savename'],
						'photodesc' => '',
						'count_view' => 0,
						'count_comment' => 0,
						'isrecommend' => 0,
						'addtime' => time(),
				);
				//插入
				if(!false == $photo_mod->create ($arrData)){
					
					//生成缩略图
					$imgpath = C('ik_attach_path').$result[0]['savefile'];
					$image = new \IKPHP\Org\Image();					
					//获取配置图像大小
					$strimgs = C('ik_simg.width').','.C('ik_mimg.width').','.C('ik_bimg.width');
					$arr_size = explode(',', $strimgs);         
		            //打开图像
		            foreach ($arr_size as $item){
		            	$image->open($imgpath);
		            	$thumb_name = $result[0]['filename'].'_'.$item.'_'.$item.'.'.$result[0]['ext']; //文件名
		            	$thumb_img = C('ik_attach_path').$result[0]['savepath'].$thumb_name;//保存路径
		            	$image->thumb($item, $item)->save($thumb_img);
		            }
		            								
					return true;
				}else{
					foreach ($photo_mod->getMessages() as $msg){
						$this->logger->log($userid.'=='.$msg);
					}
				}				
				
			}	
			return false;
		}else{
			return $this->error("你没有选择图像文件");
		}
	}
	public function infoAction($albumid){
    	//访问控制
    	if(!$this->visitor){return $this->_redirect('home/user/login');}  	
		$albumid = intval($albumid);
		$userid = $this->userid;   
		
		!empty($albumid) && $strAlbum = UserPhotoAlbum::getOneAlbum($albumid);
		if($strAlbum && $strAlbum['userid'] == $userid){ 
			if(IS_POST){
				
				$pid = $this->_post('albumface','trim,intval','0');
				$arrphotoid = $this->_post('photoid');
				$arrphotodesc = $this->_post('photodesc');
							
				foreach($arrphotodesc as $key => $item){
					if(!empty($item)){
						$photoid = $arrphotoid[$key];
						UserPhoto::findFirst("photoid ='$photoid'")->save(array('photodesc'=>clearText($item)));
					}	
				}
				if($pid>0){
					$albumface = UserPhoto::getOnePhoto($pid);
					UserPhotoAlbum::findFirst("albumid = '$albumid'")->save(array('path'=>$albumface['photopath'],'albumface'=>$albumface['photoname']));
				}
				
				return $this->_redirect('space/photos/album/'.$albumid);				
								
			}else{
				
				$smalltime = $this->_get('time','trim');
				if(!empty($smalltime)){
					$map = "userid ='$userid' AND albumid = '$albumid' AND addtime >".$smalltime;
					$arrPhoto = UserPhoto::getPhotos($map);
					$title = '完成上传！添加描述 - '.$strAlbum['albumname'];
				}else{
					$map = "userid ='$userid' AND albumid = '$albumid'";
					$arrPhoto = UserPhoto::getPhotos($map); 
					$title = '批量修改 - '.$strAlbum['albumname'];
				}

				$this->assign('strAlbum',$strAlbum);
				$this->assign('arrPhoto',$arrPhoto);
				
				$this->_config_seo ( array (
						'title' => $title,
						'subtitle'=> '相册_'.C('ik_site_title'),
						'keywords' => '',
						'description'=> '',
				) );
				$this->view->pick('photos/complete');   			
			}
		}else{
			$this->error("你没有权限访问这个页面");
		}				
	}
	//相册显示
	public function albumAction($albumid){
		$albumid = intval($albumid);
		$strAlbum = UserPhotoAlbum::getOneAlbum($albumid);
		if(empty($strAlbum)) return $this->error("没有找到你要的相册！");
		
		$strUser  = User::getOneUser($strAlbum['userid']);
		$strUser['isfollow'] = UserFollow::isFollow($this->userid, $strAlbum['userid']); //是否已关注
		
		//显示列表
		$map = "albumid = '$albumid'";
		$count = UserPhoto::count($map); 
		$pager = $this->_pager($count, 18);
		$where = array(
					"conditions" => $map,
		 			"order" => "addtime ".$strAlbum['orderid'], 
		 			"limit" => array("number"=>$pager->listRows, 'offset'=>$pager->firstRow)
		);		
		$arrItemid = UserPhoto::find($where); 
		$arrPhoto = array();
		foreach($arrItemid->toArray() as $key=>$item){
			$arrPhoto [] = UserPhoto::extPhoto($item);
		}
		$this->assign('pageUrl', $pager->show());
		$this->assign('arrPhoto', $arrPhoto);
		
		
		//获取最新评论
		$ablum_uid = $strAlbum['userid'];
		$all_photos = UserPhoto::find(array('columns'=>'photoid','conditions'=>"userid = '$ablum_uid'"));
		$str_pid ='';
		foreach ($all_photos as $ap){
			if(empty($str_pid)){
				$str_pid .= $ap->photoid;
			}else{
				$str_pid .= ','. $ap->photoid;
			}
		}			
		$arrNewComment = array();			
		if(!empty($str_pid)){
			$where = "type='UserPhoto' AND userid<>'$ablum_uid' AND typeid IN (".$str_pid.")";
			$arrNewComment = Comment::getNewComment($where, 8); 							
		}
		$this->assign('arrNewComment',$arrNewComment);		
		///////////////		
	
		
		$this->assign('strAlbum',$strAlbum);
		$this->assign('strUser',$strUser);

		if($this->userid == $strUser['userid']){
			$title = "我的相册";
		}else{
			$title = $strUser['username'].'的相册';
		}
		$this->_config_seo ( array (
				'title' => $title,
				'subtitle'=> $strAlbum['albumname'].'_相册_'.C('ik_site_title'),
				'keywords' => ikscws($strAlbum['albumname']),
				'description'=> $strAlbum['albumdesc'],
		) );
		
	}	
	//修改相册属性
	public function editAction($albumid){
    	//访问控制
    	if(!$this->visitor){return $this->_redirect('home/user/login');}  	
		$albumid = intval($albumid);
		$userid = $this->userid; 
		
		$strAlbum = UserPhotoAlbum::getOneAlbum($albumid);
		if($strAlbum['userid']==$userid){
			if(IS_POST && $this->security->checkToken() ){
			    
				$data['albumname'] = $this->_post('albumname');
				$data['albumdesc'] = $this->_post('albumdesc');
				$data['orderid'] = $this->_post('orderid','trim','desc');
				$data['privacy'] = $this->_post('privacy','intval','1');
				$data['isreply'] = $this->_post('isreply','trim','1'); // 1表示允许回复
				$data['uptime'] = time();
				
	    		//录入检查
				if( ck_strlen($data ['albumname'])>20){
					return $this->error ('相册名太长啦，最多20个字...^_^！');
				}else if( ck_strlen($data ['albumdesc'])>200){
					return $this->error ('相册描述太多了，最多200个字...^_^！');
				}else if(empty($data ['albumname']) || empty($data ['albumdesc'])){
					return $this->error ('相册标题和描述必须填写！');
				}
	
				$album_mod = UserPhotoAlbum::findFirst("albumid = '$albumid'");
				//开始创建
				if (false === $album_mod->save ($data)) {
					return $this->error ( $album_mod->getMessages() );
				}else{
					return $this->_redirect('space/photos/album/'.$albumid);
				}	
							 
			}else{
				
				$this->_config_seo ( array (
						'title' => '修改相册属性 - '.$strAlbum['albumname'],
						'subtitle'=> '相册_'.C('ik_site_title'),
						'keywords' => '',
						'description'=> '',
				) );
				$this->assign('strAlbum',$strAlbum);		
			}
		}else{
			$this->error('你没有权限更新！');
		}
	}
	//照片显示
	public function showAction($photoid = 0 ,$page = 1){
		$pid = intval($photoid);
		!empty($pid) && $strPhoto = UserPhoto::getOnePhoto($pid);
		if($strPhoto){
			
			$strAlbum = UserPhotoAlbum::getOneAlbum($strPhoto['albumid']);
			
			$order = 'addtime '.$strAlbum['orderid'];
			$arrPhotoIds = UserPhoto::find(array('columns'=>'photoid','conditions'=>"albumid = ".$strPhoto['albumid'],'order'=>$order));
			$arrPhotoId = array();
			foreach($arrPhotoIds as $item){
				$arrPhotoId[] = $item['photoid'];
			}
			
			rsort($arrPhotoId); 
			$nowkey = array_search($pid,$arrPhotoId); 
			$nowPage =  $nowkey+1 ;
			$countPage = count($arrPhotoId);
			$prev = $arrPhotoId[$nowkey - 1];
			$next = $arrPhotoId[$nowkey +1];

			$strPhoto['nexturl']  = U('space/photos/show/'.$next);
			$strPhoto['prevturl'] = U('space/photos/show/'.$prev);
			$strPhoto['nowPage'] = $nowPage;
			$strPhoto['countPage'] = $countPage;
			
			$user = User::getOneUser($strPhoto['userid']);
			
			//获取评论 类型type 类型ID typeid 返回的连接
			$order    = $this->_get('order','trim','asc');
			$isauthor = $this->_get('isauthor','trim', 0);			
			$this->assign('params', array(
							'type'=>'UserPhoto',
							'typeid'=>$photoid,
							'userid'=>$strPhoto['userid'], 
							'link'=>'space/photos/show',
							'order'=>$order,
							'isauthor'=>$isauthor,
							'page'=>$page
			));
			//评论list结束				
			
			//我的相册
			$UID = $user['userid'];
			$map = "userid = '$UID' AND privacy = 1";
			$arrAlbum = UserPhotoAlbum::getAlbums($map,'uptime desc',4);
			$this->assign('arrAlbum',$arrAlbum);
			
			
			$this->assign('strPhoto',$strPhoto);
			$this->assign('strUser',$user);
			
			if($this->userid == $strPhoto['userid']){
				$title = '我的相册 - '.$strAlbum['albumname'];
			}else{
				//浏览量+1
				$photo_mod = UserPhoto::findFirst("photoid = '$pid'");
				$count_view = intval($photo_mod->count_view)+1;
				$photo_mod->save(array('count_view'=>$count_view));
				$title = $user['username'].'的相册 - '.$strAlbum['albumname'];
			}
			$this->_config_seo ( array (
					'title' => $title,
					'subtitle'=> '_相册_'.C('ik_site_title'),
					'keywords' => ikscws($strAlbum['albumname']),
					'description'=> $strPhoto['photodesc'],
			) );

		}else{
			$this->error('呃...你想访问的照片不存在');
		}
	}
	//编辑照片描述
	public function editphotoAction(){
    	//访问控制
    	if(!$this->visitor){return $this->_redirect('home/user/login');}
    	if(IS_AJAX){
    		
    		$pid   = $this->_post('photoid','intval');
			$pinfo = $this->_post('photodesc');
			$userid = $this->userid;
			!empty($pid) && $strPhoto = UserPhoto::findFirst("photoid ='$pid'");
			if($userid>0 && $strPhoto->userid ==$userid){
				$strPhoto->save(array('photodesc'=>$pinfo));
				$this->ajaxReturn(array('r'=>1,'html'=>$pinfo));
			}else{
				$this->ajaxReturn(array('r'=>0,'error'=>'无权更新'));
			}
			    	
    	}else{
    		$this->error('呃...你无权访问该页面');
    	}
	}
	//删除照片
	public function delphotoAction($photoid){
	    //访问控制
    	if(!$this->visitor){return $this->_redirect('home/user/login');}
		$userid = $this->userid;
		$pid = intval($photoid);
		!empty($pid) && $strPhoto = UserPhoto::findFirst("photoid = '$pid' AND userid ='$userid'");

		if($strPhoto){
			if(!false == $strPhoto->delete()){
				$this->_redirect('space/photos/album/'.$strPhoto->albumid);
			}else{
				$this->error('删除失败！');
			}
			
		}else{
			$this->error('你没有删除权限');
		}
	}				
}